// pages/bookdetail/bookdetail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bookId: '', // 书籍id
    title: '', // 书籍标题
    cover: '', // 书籍封面
    author: '', // 书籍作者
    bookDetail: '', // 书籍详情
    intro: '', // 简介
    bookStyle: {}, // 书籍类型等
    littleComment: [], // 评论列表
    isShelfFlag: true, // 判断是否在书架
    isCommentFlag: false, // 评论框是否显示
    commentText: '', // 评论文本
    commentLength: '', // 评论长度
    thumbFlag: true, // 点赞状态
    nowChapterID: 0,
    defultImg: "https://pic2.zhimg.com/v2-ab9549c7127bef7b692021e83d851f07_1440w.jpg?source=172ae18b", // 默认图
    defUserCover: "http://thirdwx.qlogo.cn/mmopen/vi_32/0LcGkzxFMSb99JBwpWpbxQh9ORg4kuJU60Efn29Zwa8xxVSj6nGqnesI6Tkm4I9muSrIzUxDttjFRu5AWAxtng/132", // 用户默认头像
  },

  // 点赞
  thumb(e) {
    let id = e.currentTarget.dataset.commentid
    let index =  this.data.littleComment.findIndex((item) => item.commentId == id)
    if (index != -1) {
      console.log(index);
      this.data.littleComment[index].isPraise = 1
      this.data.littleComment[index].likes += 1
      this.setData({
        littleComment: this.data.littleComment
      })
      wx.setStorageSync('thumbList', [id,...wx.getStorageSync('thumbList')])
    }
    console.log(wx.getStorageSync('thumbList'));
  },
  // 取消点赞
  cancelThumb(e) {
    let id = e.currentTarget.dataset.commentid
    let index =  this.data.littleComment.findIndex((item) => item.commentId == id)
    let thumbList = wx.getStorageSync('thumbList')
    console.log(thumbList);
    let i = thumbList.findIndex((item) => item == id)
    console.log(i);
    wx.getStorageSync('thumbList')
    if (index != -1) {
      // console.log(index);
      this.data.littleComment[index].isPraise = 0
      this.data.littleComment[index].likes -= 1
      this.setData({
        littleComment: this.data.littleComment
      })
      
    }
    if (i != -1) {
      thumbList.splice(i,1)
      wx.setStorageSync('thumbList', thumbList)
    }
    
  },

  // 获取书籍详情
  getbookDetail() {
    // 展示loading效果
    wx.showLoading({
      title: '数据加载中...',
    })

    wx.request({
      url: 'https://apic.netstart.cn/yunyuedu/book/info.json?sourceUuid=' + this.data.bookId,
      method: 'GET',
      success: (res) => {
        this.setData({
          bookDetail: res.data.data.book,
          cover: res.data.data.book.cover,
          author: res.data.data.book.author
        })
        console.log(res.data.data.book);
        // console.log(this.data.bookDetail);
      },
      // 隐藏loading效果
      complete: () => {
      }
    })
    wx.request({
      url: 'https://apic.netstart.cn/yunyuedu/book/getsub.json?id=' + this.data.bookId +'&title=' + this.data.title,
      method: 'GET',
      success: (res) => {
        this.setData({
          intro: res.data.feed.entry.summary,
          bookStyle: res.data.feed.entry['pris:book']
        })
        // console.log(res.data.data.book);
        console.log(this.data.bookStyle);
        console.log(res);
      }
    })
  },

  // 获取评论数据1
  getCommentData() {

    if (wx.getStorageSync('commentList')) {
      let commentList = wx.getStorageSync('commentList')
      let nowCommentList = commentList.filter((item) => {
        return item.bookId == this.data.bookId
      })
      console.log(nowCommentList);
      let index = commentList.findIndex((item) => item.bookId == this.data.bookId)
      if (nowCommentList.length) {
        console.log(index);

        // 展示loading效果
        wx.showLoading({
          title: '数据加载中...',
        })
        wx.request({
          url: 'https://apic.netstart.cn/yunyuedu/comment/getComments.json?bookId=' + this.data.bookId,
          method: 'GET',
          success: (res) => {
            this.setData({
              littleComment: res.data.all.list.slice(0,5)
            })
            // console.log(res);
            console.log(this.data.littleComment);
          },
          // 隐藏loading效果
          complete: () => {
            this.setData({
              littleComment: [...nowCommentList,...this.data.littleComment]
            })
            if (wx.getStorageSync('thumbList')) {
              let thumbList = wx.getStorageSync('thumbList')
              thumbList.forEach((item) => {
                this.data.littleComment.forEach((i) => {
                  if (item == i.commentId) {
                    i.likes += 1
                    i.isPraise = 1
                  }
                })
              })
              this.setData({
                littleComment: this.data.littleComment
              })
            }
            console.log(this.data.littleComment);
            wx.hideLoading()
          }
        })
        
      } else {
        console.log(2222);
        this.getCommend()
      }
      
    } else {
      console.log(33333);
      this.getCommend()
    }
  },
  //  开始阅读
  goPage(){
     wx.navigateTo({
       url: `/pages/bookcontent/bookcontent?bookId=${this.data.bookId}`,
     })
  },
  // 继续阅读
  keepPage() {
    wx.navigateTo({
      url: `/pages/bookcontent/bookcontent?bookId=${this.data.bookId}&nowChapterID=${this.data.nowChapterID}`,
    })
  },
  // 获取评论数据2
  getCommend() {
    // 展示loading效果
    wx.showLoading({
      title: '数据加载中...',
    })
    wx.request({
      url: 'https://apic.netstart.cn/yunyuedu/comment/getComments.json?bookId=' + this.data.bookId,
      method: 'GET',
      success: (res) => {
        this.setData({
          littleComment: res.data.all.list.slice(0,5)
        })
        // console.log(res);
        console.log(this.data.littleComment);
      },
      // 隐藏loading效果
      complete: () => {
        if (wx.getStorageSync('thumbList')) {
          let thumbList = wx.getStorageSync('thumbList')
          thumbList.forEach((item) => {
            this.data.littleComment.forEach((i) => {
              if (item == i.commentId) {
                i.likes += 1
                i.isPraise = 1
              }
            })
          })
          this.setData({
            littleComment: this.data.littleComment
          })
        }
        wx.hideLoading()
      }
    })
  },

  // 加入书架
  addShelf() {  
    
      if (!wx.getStorageSync('bookShelf')) {
        let obj = {
          bookId: this.data.bookId,
          cover: this.data.cover,
          title: this.data.title,
          author: this.data.author,
        }
        wx.setStorageSync('bookShelf',[obj])
      } else {
        console.log(111);
        let bookshelf = wx.getStorageSync('bookShelf')
        let obj = {
          bookId: this.data.bookId,
          cover: this.data.cover,
          title: this.data.title,
          author: this.data.author,
        }
        wx.setStorageSync('bookShelf',[...new Set([obj,...bookshelf])])
      }
      wx.showToast({
        title: '加入成功 ~',
        icon: 'none',
        success: res => {
          this.setData({
            isShelfFlag: false
          })
        }
      })
    
    console.log(this.data.bookId,this.data.cover,this.data.title,this.data.author);
  },
  
  // 判断是否已在书架
  getInShelf() {
    if(wx.getStorageSync('bookShelf')) {
      let bookShelfList = wx.getStorageSync('bookShelf')
      bookShelfList.forEach((item) => {
        if (item.bookId === this.data.bookId) {
          this.setData({
            isShelfFlag: false
          })
        }
      })
    }
  },
  // 写评论
  writeComment() {
    // 评论前判断是否登录
    if(wx.getStorageSync('token')) {
      this.setData({
        isCommentFlag: true
      })

    } else {
      wx.showToast({
        title: '请先进行登录~',
        icon: 'none',
      })
      wx.getUserProfile({
        desc: '授权后可提升更多体验~',
        success: res => {
          console.log('授权成功~',res);
          wx.setStorageSync('token', res.userInfo)
          wx.showToast({
            title: '登录成功~',
            icon: 'none',
          })
        },
        fail(res) {
          console.log('授权失败~',res);
        }
      })
    }

    
  },

  // 发送评论
  sendComment() {
    var timeStamp = Date.parse(new Date())
    let obj = {
      avatar: "https://thirdwx.qlogo.cn/mmopen/vi_32/BVNBTOnodOS8tvuQOXSPz9c004DoPtvaZXBKUIicrrmrGFwic3DbZxHEacDcaiaWguWWvrSU7mhGd2y8ajW86lkkg/132",
      comment: this.data.commentText,
      commentId: timeStamp,
      userLevel: "1",
      nickName: "故涤",
      likes: 0,
      bookId: this.data.bookId,
      time: timeStamp,
      isPraise: 0
    }

    this.setData({
      littleComment: [obj,...this.data.littleComment],
      isCommentFlag: false,
      commentText: '',
      commentLength: ''
    })

    wx.showToast({
      title: '评论成功~',
      icon: 'none',
    })

    wx.setStorageSync('commentList', [obj,...wx.getStorageSync('commentList')])
    console.log(obj);
  },

  // 取消评论
  cancelComment() {
    this.setData({
      isCommentFlag: false
    })
  },
  // 评论事件
  changeText(e) {
    this.setData({
      commentText: e.detail.value,
      commentLength: (e.detail.value).trim()
    })
  },

  // 发生图片错误
  errDetails() {
    this.data.bookDetail.cover = this.data.defultImg
    this.setData({
      bookDetail: this.data.bookDetail
    })
  },

   /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      bookId: options.id,
      title: options.title
    })
    
    console.log(this.data.nowChapterID);
    this.getInShelf()
    this.getbookDetail()
    this.getCommentData()
    
    // console.log(this.data.bookId,this.data.title);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (wx.getStorageSync('historyCatalog')) {
      let arr = wx.getStorageSync('historyCatalog')
      let index = arr.findIndex((item) => item.bookId == this.data.bookId)
      if (index != -1) {
        this.setData({
          nowChapterID: arr[index].historyId
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  console.log(123)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})